package redis

import (
	"context"
	"log"
	"time"

	"github.com/spf13/viper"

	"github.com/go-redis/redis/v8"
)

type redisService struct {
	rdb *redis.Client
}

type RedisService interface {
	Client() *redis.Client
	SetString(key, value string, ttl time.Duration) error
	Get(key string) (string, error)
}

func NewRedisClient() RedisService {
	url := viper.GetString("redis.url")

	opts, err := redis.ParseURL(url)
	if err != nil {
		log.Fatal("new redis service failed, ", err)
		return nil
	}

	client := redis.NewClient(opts)

	return &redisService{
		rdb: client,
	}
}

func (svc *redisService) Client() *redis.Client {
	return svc.rdb
}

func (svc *redisService) SetString(key, value string, ttl time.Duration) error {
	ctx := context.Background()
	return svc.rdb.Set(ctx, key, value, ttl).Err()
}

func (svc *redisService) Get(key string) (string, error) {
	ctx := context.Background()
	return svc.rdb.Get(ctx, key).Result()
}
